package game.module.qzmj.logic;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import game.entity.PlayingRole;
import game.module.qzmj.QzmjConstants;
import game.module.qzmj.bean.QzmjRound;
import game.session.GlobalTimer;
import game.session.SessionManager;
import io.netty.util.Timeout;
import io.netty.util.TimerTask;
import lion.common.IdWorker;
import lion.netty4.message.GamePlayer;
import lion.netty4.message.INetty4EventHandler;
import lua.LuaMessageQzmj.PushQzmjRoomDissmiss;

public class QzmjRoomManager implements INetty4EventHandler{

	public static final Logger logger = LoggerFactory.getLogger(QzmjRoomManager.class);
	
	private GlobalTimer globalTimer = GlobalTimer.getInstance();
	
	private Map<String ,MapValueHolder> roomTimeoutMap =new ConcurrentHashMap<String, MapValueHolder>();
	
	private IdWorker uuIdGenerator;

	public static final int SESSION_TIMEOUT_DELAY = QzmjConstants.AUTODISSTIME;// 150秒
	
	public static class SingletonHolder {
		static QzmjRoomManager instance = new QzmjRoomManager();
	}

	public static QzmjRoomManager getInstance() {
		return SingletonHolder.instance;
	}
	
	public void cancledismiss(final String roomid) {
		//被移除了
		if (!roomTimeoutMap.containsKey(roomid)) {
			return ;
		}
		MapValueHolder mapValueHolder =roomTimeoutMap.get(roomid);
		Timeout curTimeout = mapValueHolder.getWheelTimeout();
		curTimeout.cancel();
		roomTimeoutMap.remove(roomid);
	}
	//提前执行
	public void advanceCancel(Integer playerId) {
		final QzmjRound mj =   QzmjDatamanager.getInstance().getMjRoom(playerId);
		if(mj==null) {
			return;//数据有误
		}
		cancledismiss(mj.getRoomUuid());
		QzmjLogic.getInstance().RoundOver(mj); //移除房间
		List<Integer> playerList =  mj.getPlayerIds();
		PushQzmjRoomDissmiss pushMsg = new PushQzmjRoomDissmiss();
		pushMsg.index =(byte) playerList.indexOf(playerId);
		pushMsg.state = 1;
		for(Integer aplayer:playerList) {
			PlayingRole pr = SessionManager.getInstance().getPlayer(aplayer);
			if (pr != null && pr.isChannelActive()) {
				pr.writeAndFlush(pushMsg.build(pr.alloc()));
				// 推送关于出牌的信息
			}
		}
		QzmjLogic.getInstance().testRoundOver(mj);
	}
	
	public void createtRemoveMjroom(final Integer playerId) {
		final QzmjRound mj =   QzmjDatamanager.getInstance().getMjRoom(playerId);
		if(mj==null) {
			return;//数据有误
		}
		if (roomTimeoutMap.containsKey(mj.getRoomUuid())) {
			return ;//任务已经存在
		}
		Timeout curTimeout = globalTimer.newTimeout(new TimerTask() {
			
			@Override
			public void run(Timeout timeout) throws Exception {
				// TODO Auto-generated method stub
				logger.info("dissmiss mjroom by vote playerid={} ",playerId);
				MapValueHolder oldValueHolder = roomTimeoutMap.get(mj.getRoomUuid());
				QzmjRound mjs = oldValueHolder.getQzmjround();
				PushQzmjRoomDissmiss pushMsg = new PushQzmjRoomDissmiss();
				List<Integer> playerList =  mjs.getPlayerIds();
				QzmjLogic.getInstance().RoundOver(mjs); //移除房间
				pushMsg.index = (byte) playerList.indexOf(playerId);
				pushMsg.state = 1;
				for(Integer aplayer:playerList) {
					PlayingRole pr = SessionManager.getInstance().getPlayer(aplayer);
					if (pr != null && pr.isChannelActive()) {
						pr.writeAndFlush(pushMsg.build(pr.alloc()));
						// 推送关于出牌的信息
					}
				}
				if(mjs!=null) {
					
					QzmjLogic.getInstance().testRoundOver(mj);
				}
				roomTimeoutMap.remove(mj.getRoomUuid());
			}
		}, SESSION_TIMEOUT_DELAY);
		List<Integer> playerList =  mj.getPlayerIds();
		mj.setCreateVotePlayerID((byte)playerList.indexOf(playerId));
		mj.setStartvoteTime(System.currentTimeMillis());
		MapValueHolder mapValueHolder = new  MapValueHolder(curTimeout,mj);
		roomTimeoutMap.put(mj.getRoomUuid(), mapValueHolder);
	}
	
	@Override
	public void channelInactive(GamePlayer gamePlayer) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void readTimeout(GamePlayer gamePlayer) {
		logger.info("read timeout,close socket!,addr={}", gamePlayer.getAddress());
		gamePlayer.close();
		
	}

}
class MapValueHolder {
	private Timeout wheelTimeout;
	private QzmjRound qzmjround;

	public MapValueHolder(Timeout wheelTimeout, QzmjRound qzmjround) {
		super();
		this.setWheelTimeout(wheelTimeout);
		this.setQzmjround(qzmjround);
	}

	public Timeout getWheelTimeout() {
		return wheelTimeout;
	}

	public void setWheelTimeout(Timeout wheelTimeout) {
		this.wheelTimeout = wheelTimeout;
	}

	public QzmjRound getQzmjround() {
		return qzmjround;
	}

	public void setQzmjround(QzmjRound qzmjround) {
		this.qzmjround = qzmjround;
	}

	
}
